module app.controller.base;
import hunt.application;
import std.experimental.logger;
import std.conv;
public import app.helper.appinfo;
public import app.exception;

import core.vararg;
public import std.digest.md;
import std.string;
import std.base64;
import deimos.openssl.aes;
import app.utils;

class BaseController : Controller
{
	
	
	string getBody(Request req)
	{
		if(req.Body is null)
			return "";
		req.Body.rest(0);
		ubyte[] reqBody;
		req.Body.readAll((in ubyte[] data){
				reqBody ~= data;
			});
		return cast(string)reqBody;
	}
	private void checkParamsRequired( ...)
	{
		for (int i = 0; i < _arguments.length; i++)
		{
			if (_arguments[i] == typeid(string))
			{
				string p = va_arg!(string)(_argptr);
				if(p.length)
					continue;
				throwExceptionBuild!"Argument"("param is required  : " ~ p.stringof);	
			}
			
		}
	}
	
	string checkSign(Request req)
	{
		import std.string;
		string appid = req.header("X-Spay-AppId");
		string apiversion = req.header("X-Spay-ApiVersion");
		string sign = req.header("X-Spay-Sign");
		string signTime = req.header("X-Spay-Request-Time");
		string signedData = "";
		
		checkParamsRequired(appid,apiversion,sign,signTime);
		
		string method = req.method.toLower();
		if(method == "get" || method == "delete")
		{
			signedData = req.header("X-Spay-Request-Data");
		}
		else if(method == "post" || method == "put")
		{
			signedData = getBody(req);
		}
		else{
			throwExceptionBuild!"Argument"("not support method " ~ method);	
		}
		
		IAppInfo appinfo = new AppInfoInner();
		SAppInfo sinfo = appinfo.getSAppInfoById(appid);
		if(sinfo.status == 0){
			throwExceptionBuild!"AppIdNotFound"("app id is not found or remove ");	
		}
		string ckSign = toHexString(md5Of(signedData ~ signTime ~ sinfo.appSecretKey));
		if(ckSign.toLower() != sign)
		{
			throwExceptionBuild!"Sign"("sign error : ckSign: " ~ ckSign ~" sign:" ~sign);	
		}
		
		//AES 解密获取data
		return aes256decrypt(signedData, sinfo.appSecretKey);
	}
	
	
}

